package com.yzx.lifeassistants.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.balysv.materialripple.MaterialRippleLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.yzx.lifeassistants.GlobalParams;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.activity.FeedbackActivity;
import com.yzx.lifeassistants.activity.LoginActivity;
import com.yzx.lifeassistants.activity.UserSettingAtivity;
import com.yzx.lifeassistants.base.ActivityCollector;
import com.yzx.lifeassistants.base.BaseApplication;
import com.yzx.lifeassistants.common.CommonConstant;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.SpUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.RoundedImageView;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 我
 * @author: yzx
 * @time: 2016-4-24 下午1:50:24
 */
public class MeFragment extends Fragment implements OnClickListener {

	private RelativeLayout userSettingRL;// 用户设置
	private RoundedImageView avatarIV;// 头像
	private TextView nickTV;// 昵称
	private TextView emailTV;// 邮箱
	private TextView remberPswTV;// 记住密码
	private CheckBox remberPswCB;// 记住密码
	private TextView autoLoginTV;// 自动登录
	private CheckBox autoLoginCB;// 自动登录
	private TextView infoTV;// 推送通知
	private CheckBox infoCB;// 推送通知
	private TextView updateTV;// 检查更新
	private TextView feedBackTV;// 意见反馈
	private TextView logoutTV;// 注销用户
	private TextView quitTV;// 退出应用

	protected SpUtils sputil;// 保存
	private Drawable manDrawable;// 男
	private Drawable womenDrawable;// 女
	private CircularLoadingDialog dialog;// 加载框

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (null == sputil) {
			sputil = new SpUtils(getActivity(), CommonConstant.SP_FAIL_NAME);
		}
	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_me, container, false);
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		setListener();
		initMaterialRipple();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		userSettingRL = (RelativeLayout) getView().findViewById(
				R.id.me_user_setting_rl);
		avatarIV = (RoundedImageView) getView().findViewById(
				R.id.me_user_avatar_iv);
		nickTV = (TextView) getView().findViewById(R.id.me_user_nick_tv);
		emailTV = (TextView) getView().findViewById(R.id.me_user_email_tv);
		remberPswTV = (TextView) getView().findViewById(R.id.me_rember_pwd_tv);
		remberPswCB = (CheckBox) getView().findViewById(R.id.me_rember_psw_cb);
		autoLoginTV = (TextView) getView().findViewById(R.id.me_auto_login_tv);
		autoLoginCB = (CheckBox) getView().findViewById(R.id.me_auto_login_cb);
		infoTV = (TextView) getView().findViewById(R.id.me_info_tv);
		infoCB = (CheckBox) getView().findViewById(R.id.me_info_cb);
		updateTV = (TextView) getView().findViewById(R.id.me_update_tv);
		feedBackTV = (TextView) getView().findViewById(R.id.me_feedback_tv);
		logoutTV = (TextView) getView().findViewById(R.id.me_logout_tv);
		quitTV = (TextView) getView().findViewById(R.id.me_quit_tv);

	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		userSettingRL.setOnClickListener(this);
		remberPswCB.setOnClickListener(this);
		autoLoginCB.setOnClickListener(this);
		infoCB.setOnClickListener(this);
		updateTV.setOnClickListener(this);
		feedBackTV.setOnClickListener(this);
		logoutTV.setOnClickListener(this);
		quitTV.setOnClickListener(this);

	}

	/**
	 * 
	 * @Description: 瓷砖特效
	 */
	private void initMaterialRipple() {
		List<View> views = new ArrayList<View>();
		views.add(userSettingRL);
		views.add(remberPswTV);
		views.add(autoLoginTV);
		views.add(infoTV);
		views.add(updateTV);
		views.add(feedBackTV);
		views.add(logoutTV);
		views.add(quitTV);
		for (View view : views) {
			// 动态特效
			MaterialRippleLayout
					.on(view)
					.rippleColor(
							Color.parseColor(CommonConstant.RIPPLE_COLOR_LITHT))
					.rippleAlpha(CommonConstant.RIPPLE_ALPHA).rippleHover(true)
					.create();
		}

	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(getActivity());
		manDrawable = getResources().getDrawable(R.drawable.icon_me_male);
		manDrawable.setBounds(0, 0, manDrawable.getMinimumWidth(),
				manDrawable.getMinimumHeight());
		womenDrawable = getResources().getDrawable(R.drawable.icon_me_female);
		womenDrawable.setBounds(0, 0, womenDrawable.getMinimumWidth(),
				womenDrawable.getMinimumHeight());
		// 昵称
		nickTV.setText(GlobalParams.userInfo.getNick());
		// 性别
		if (GlobalParams.userInfo.getSex() != null
				&& GlobalParams.userInfo.getSex()) {
			nickTV.setCompoundDrawables(womenDrawable, null, null, null);
		} else {
			nickTV.setCompoundDrawables(manDrawable, null, null, null);
		}
		// 邮箱
		emailTV.setText(GlobalParams.userInfo.getUsername());
		// 是否记住密码
		Boolean remberPwd = sputil.getValue(CommonConstant.REMBER_PWD_KEY,
				false);
		remberPswCB.setChecked(remberPwd);
		// 是否自动登陆
		Boolean autoLogin = sputil.getValue(CommonConstant.AUTO_LOGIN_KEY,
				false);
		autoLoginCB.setChecked(autoLogin);
		// 是否接收通知
		Boolean info = sputil.getValue(CommonConstant.INFO_KEY, false);
		infoCB.setChecked(info);
		// 头像
		BmobFile avatarFile = GlobalParams.userInfo.getAvatar();
		if (null != avatarFile) {
			ImageLoader.getInstance().displayImage(
					avatarFile.getFileUrl(getActivity()),
					avatarIV,
					BaseApplication.getInstance().getOptions(
							R.drawable.user_icon_default_main),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
						}
					});
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.me_user_setting_rl: {// 个人设置
			Intent intent = new Intent(getActivity(), UserSettingAtivity.class);
			startActivityForResult(intent, 1234);
			break;
		}
		case R.id.me_rember_psw_cb: {// 记住密码
			switchRemberPwd();
			break;
		}
		case R.id.me_auto_login_cb: {// 自动登录
			switchAutoLogin();
			break;
		}
		case R.id.me_info_cb: {// 推送通知
			switchInfo();
			break;
		}
		case R.id.me_update_tv: {// 检查更新
			CheckUpdate();
			break;
		}
		case R.id.me_logout_tv: {// 用户登出
			loginOut();
			break;
		}
		case R.id.me_feedback_tv: {// 意见反馈
			feedback();
			break;
		}
		case R.id.me_quit_tv: {// 退出应用
			quitApp();
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 检查更新
	 */
	private void CheckUpdate() {
		dialog.show();
		// 关闭Toast
		BmobUpdateAgent.setUpdateCheckConfig(false);
		// 不只是在WiFi条件下更新
		BmobUpdateAgent.setUpdateOnlyWifi(false);
		// 设置监听
		BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {

			@Override
			public void onUpdateReturned(int updateStatus,
					UpdateResponse updateInfo) {
				dialog.dismiss();
				switch (updateStatus) {
				case UpdateStatus.Yes: {// 版本有更新
					break;
				}
				case UpdateStatus.No: {// 版本无更新
					showToast("目前版本为最新版~", true);
					break;
				}
				case UpdateStatus.IGNORED: {// 忽略更新
					showToast("该版本已被忽略更新~", true);
					break;
				}
				case UpdateStatus.TimeOut: {// 查询出错或超时
					showToast("网络超时，请检查您的手机网络~", false);
					break;
				}
				case UpdateStatus.EmptyField: {// 此提示只是提醒开发者关注那些必填项，测试成功后，无需对用户提示
					LogcatUtils
							.e("请检查你AppVersion表的必填项，1、target_size（文件大小）是否填写；2、path或者android_url两者必填其中一项。");
					showToast("更新失败，请重试~", false);
					break;
				}
				case UpdateStatus.ErrorSizeFormat: {// 此提示只是提醒开发者关注那些必填项，测试成功后，无需对用户提示
					LogcatUtils
							.e("请检查target_size填写的格式，请使用file.length()方法获取apk大小。");
					showToast("更新失败，请重试~", false);
					break;
				}
				default: {
					showToast("更新失败，请重试~", false);
					break;
				}
				}
			}
		});
		// 更新
		BmobUpdateAgent.forceUpdate(getActivity());
	}

	/**
	 * 
	 * @Description: 切换是否记住密码
	 */
	private void switchRemberPwd() {
		if (remberPswCB.isChecked()) {
			sputil.setValue(CommonConstant.REMBER_PWD_KEY, true);
		} else {
			sputil.setValue(CommonConstant.REMBER_PWD_KEY, false);
			autoLoginCB.setChecked(false);
			sputil.setValue(CommonConstant.AUTO_LOGIN_KEY, false);
		}
	}

	/**
	 * 
	 * @Description: 切换是否自动登录
	 */
	private void switchAutoLogin() {
		if (autoLoginCB.isChecked()) {
			sputil.setValue(CommonConstant.AUTO_LOGIN_KEY, true);
			remberPswCB.setChecked(true);
			sputil.setValue(CommonConstant.REMBER_PWD_KEY, true);
		} else {
			sputil.setValue(CommonConstant.AUTO_LOGIN_KEY, false);
		}
	}

	/**
	 * 
	 * @Description: 切换是否接收通知
	 */
	private void switchInfo() {
		if (infoCB.isChecked()) {
			sputil.setValue(CommonConstant.INFO_KEY, true);
		} else {
			sputil.setValue(CommonConstant.INFO_KEY, false);
		}
	}

	/**
	 * 
	 * @Description: 用户注销
	 */
	private void loginOut() {
		new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
				.setTitleText("你确定要退出该用户吗？")
				.setContentText("退出后将收不到消息！！！")
				.setCancelText("取消")
				.setConfirmText("确定")
				.showCancelButton(true)
				.setCancelClickListener(null)
				.setConfirmClickListener(
						new SweetAlertDialog.OnSweetClickListener() {

							@Override
							public void onClick(

							SweetAlertDialog sweetAlertDialog) {// 用户登出
								BmobUser.logOut(getActivity());
								// 清除是否记住密码以及自动登录
								sputil.setValue(CommonConstant.REMBER_PWD_KEY,
										false);
								sputil.setValue(CommonConstant.AUTO_LOGIN_KEY,
										false);
								Intent intent = new Intent(getActivity(),
										LoginActivity.class);
								intent.putExtra(CommonConstant.TO_LOGIN_NAME,
										CommonConstant.FROM_LOGOUT_TO_LOGIN_KEY);
								startActivity(intent);

							}
						}).show();
	}

	/**
	 * 
	 * @Description: 意见反馈
	 */
	private void feedback() {
		Intent intent = new Intent(getActivity(), FeedbackActivity.class);
		startActivityForResult(intent, CommonConstant.REQUESTCODE_FEEDBACK);
	}

	/**
	 * 
	 * @Description: 退出应用
	 */
	private void quitApp() {
		new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
				.setTitleText(
						"你确定要退出" + getResources().getString(R.string.app_name)
								+ "应用吗？")
				.setContentText("退出后将收不到消息！！！")
				.setCancelText("取消")
				.setConfirmText("确定")
				.showCancelButton(true)
				.setCancelClickListener(null)
				.setConfirmClickListener(
						new SweetAlertDialog.OnSweetClickListener() {

							@Override
							public void onClick(

							SweetAlertDialog sweetAlertDialog) {// 退出应用
								ActivityCollector.finishAll();

							}
						}).show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == CommonConstant.REQUESTCODE_FEEDBACK) {
			if (resultCode == CommonConstant.RESULTCODE_FEEDBACK_CANCEL) {
				// 取消反馈
				LogcatUtils.i("已取消反馈意见");
			} else if (resultCode == CommonConstant.RESULTCODE_FEEDBACK_OK) {
				// 反馈成功
				showToast("感谢您的宝贵意见~", true);
			}
		}
		if (1234 == requestCode) {// 更新资料
			// 昵称
			nickTV.setText(GlobalParams.userInfo.getNick());
			// 性别
			if (GlobalParams.userInfo.getSex() != null
					&& GlobalParams.userInfo.getSex()) {
				nickTV.setCompoundDrawables(womenDrawable, null, null, null);
			} else {
				nickTV.setCompoundDrawables(manDrawable, null, null, null);
			}
			// 头像
			BmobFile avatarFile = GlobalParams.userInfo.getAvatar();
			if (null != avatarFile) {
				ImageLoader.getInstance().displayImage(
						avatarFile.getFileUrl(getActivity()),
						avatarIV,
						BaseApplication.getInstance().getOptions(
								R.drawable.user_icon_default_main),
						new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view,
										loadedImage);
							}
						});
			}
			// 更新侧滑菜单的用户头像
			LeftMenuFragment leftMenu = (LeftMenuFragment) getFragmentManager()
					.findFragmentById(R.id.menu_frame);
			leftMenu.onResume();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(getActivity(), message, R.id.me_top_rl);
		} else {
			ToastUtils.showAlertToast(getActivity(), message, R.id.me_top_rl);
		}

	}
}
